package com.phz.springcloud.study.service;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.phz.springcloud.study.client.CuccScoreClient;
import com.phz.springcloud.study.dao.UserDao;
import com.phz.springcloud.study.entity.User;

@Service
@Transactional
public class UserService {
	
	protected static final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	private static final ObjectMapper mapper = new ObjectMapper();
	
	public static final String REGESITER_ROUTINGKEY = "register-queue";
	
	public static final String REGESITER_SCORE_ROUTINGKEY = "register-score-queue";
	
	public static final String SCORE_ROUTINGKEY = "score-queue";
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	 @Autowired
	 private AmqpTemplate rabbitTemplate;
	 

	/**
	 * 用户注册流程
	 * <p>
	 * 1. 写入用户表
	 * <p>
	 * 2. 发送邮件
	 *  <p>
	 * 3. 查询用户的信用评分
	 *  <p>
	 * 4. 建立用户账户表
	 *  <p>
	 * 2-4个流程放入消息队列进行处理。
	 * @param user
	 * @throws JsonProcessingException 
	 * @throws AmqpException 
	 */
	public  void register(User user) throws AmqpException, JsonProcessingException{
		save(user);
		// 发送消息队列
		rabbitTemplate.convertAndSend(REGESITER_ROUTINGKEY, mapper.writeValueAsString(user));
		logger.debug("--------user:"+user.toString());
	}
	
	
	public  String registerAndGetScore(User user) throws AmqpException, JsonProcessingException{
		save(user);
		// 发送消息队列
		String  score = rabbitTemplate.convertSendAndReceive(REGESITER_SCORE_ROUTINGKEY, mapper.writeValueAsString(user)).toString();
		logger.debug("注册成功了------------------score:"+score);
		return score;
	}
	
	public  void registerAndSubscribe(User user) throws AmqpException, JsonProcessingException{
		save(user);
		logger.debug("--------user:"+user.toString());
		// 发送消息队列
		rabbitTemplate.convertAndSend(REGESITER_ROUTINGKEY, mapper.writeValueAsString(user));
	}
	
	

	public void save(User user) {
		User exist = userDao.findByPhone(user.getPhone());
		Assert.isNull(exist, "该手机号已经存在:"+user.getPhone());
		user.setRegisterTime(new Date());
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		userDao.save(user);
	}

}
